package com.example.guet_assistant.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.guet_assistant.domain.vo.MessageVO;
import com.example.guet_assistant.domain.vo.ReturnMessageVO;
import com.example.guet_assistant.handler.WebSocketHandler;
import com.example.guet_assistant.mapper.MessageMapper;
import com.example.guet_assistant.mapper.MessageTypeMapper;
import com.example.guet_assistant.pojo.entity.Message;
import com.example.guet_assistant.pojo.entity.MessageType;
import com.example.guet_assistant.pojo.entity.User;
import com.example.guet_assistant.result.Result;
import com.example.guet_assistant.service.MessageService;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author Lenovo
* @description 针对表【message】的数据库操作Service实现
* @createDate 2024-11-03 15:54:28
*/
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService{

    @Autowired
    MessageMapper messageMapper;

    @Autowired
    MessageTypeMapper messageTypeMapper;

    public static final String WEATHER_NOW="https://devapi.qweather.com/v7/weather/now?location=101300507&key=4a1364c86d344f36b0927b41b5f4b8ed";

    public static final String WEATHER_7D="https://devapi.qweather.com/v7/weather/7d?location=101300507&key=4a1364c86d344f36b0927b41b5f4b8ed";

    public static final String AIR_NOW="https://devapi.qweather.com/v7/air/now?location=101300507&key=4a1364c86d344f36b0927b41b5f4b8ed";

    @Override
    public  List<Message> publishMessage(MessageVO messageVO) throws Exception{
        List<String> userIds = messageVO.getUserId();
        List<Message> messages = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for(String userId : userIds){
            Message message = new Message();
            message.setId(messageVO.getId());
            message.setTitle(messageVO.getTitle());
            message.setContent(messageVO.getContent());
            message.setUserId(userId);
            message.setStatus(0);
            // 格式化 publishTime 和 regularTime
            Date publishTime = dateFormat.parse(messageVO.getPublishTime());
            Date regularTime = dateFormat.parse(messageVO.getRegularTime());

            if (publishTime != null) {
                message.setPublishTime(dateFormat.parse(dateFormat.format(publishTime)));
            }

            if (regularTime != null) {
                message.setRegularTime(dateFormat.parse(dateFormat.format(regularTime)));
            }

            message.setMessageType(messageVO.getMessageType());

            messages.add(message);
        }
        return messages;
    }

    @Override
    public Result<Message> regularMessage(Message message){
        message.setStatus(1);
        messageMapper.updateById(message);
        return Result.success(message);
    }

    @Override
    public Result<List<ReturnMessageVO>> getTitleList(String userId, String type) {
        // 创建一个 Map 来存储所有的消息类型及其对应的标题列表
        List<ReturnMessageVO> returnMessageVOList = new ArrayList<>();

        if(type.equals("校园公告")){
            List<Message> messages = messageMapper.selectList(new QueryWrapper<Message>().eq("message_type", type));

            for (Message message : messages) {
                Integer id = message.getId();
                String title = message.getTitle();
                Date publishTime = message.getPublishTime();
                ReturnMessageVO returnMessageVO = new ReturnMessageVO(id, title, publishTime);

                returnMessageVOList.add(returnMessageVO);
            }
        }

        // 查询所有符合条件的消息
        List<Message> messages = messageMapper.selectList(new QueryWrapper<Message>().eq("user_id", userId).eq("message_type", type));

        // 遍历消息列表并按 type 分类
        for (Message message : messages) {
            Integer id = message.getId();
            String title = message.getTitle();
            Date publishTime = message.getPublishTime();
            ReturnMessageVO returnMessageVO = new ReturnMessageVO(id, title, publishTime);

            returnMessageVOList.add(returnMessageVO);
        }

        return Result.success(returnMessageVOList);
    }




    @Override
    public Result<List<String>> getMessageList(Integer id, String title) {
        List<String> contentList = new ArrayList<>();
        List<Message> messages = messageMapper.selectList(new QueryWrapper<Message>()
                .eq("title", title)
                .eq("id", id));

        for(Message message : messages){
            contentList.add(message.getContent());
        }
        return Result.success(contentList);
    }


    @Override
    public List<Message> findMessagesToPublish(String currentTime) throws Exception{
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentDate = formatter.parse(currentTime);
        return messageMapper.selectList(
            new QueryWrapper<Message>().le("regular_time", currentDate).eq("status", 0)
        );
    }

    @Override
    public Result<List<String>> getMessageType(){
        List<MessageType> messageTypes = messageTypeMapper.selectList(new QueryWrapper<>());
        List<String> fieldValues = messageTypes.stream()
                .map(MessageType::getType) // 提取指定字段
                .collect(Collectors.toList());
        return Result.success(fieldValues);
    }

    @Override
    public Result getWeather()    throws Exception {
        //创建要返回的map对象
        HashMap<String, Object> map = new HashMap<>();
        //获取灵川县今天的天气情况
        String  s1= doGet(WEATHER_NOW);
        JSONObject jsonObject = JSON.parseObject(s1);
        String weatherNow = jsonObject.getString("now");
        map.put("toadyWeather", JSON.parseObject(weatherNow, HashMap.class));
        //获取灵川县最近7天的天气情况
        String  s2= doGet(WEATHER_7D);
        jsonObject = JSON.parseObject(s2);
        JSONArray dailyArray = jsonObject.getJSONArray("daily");
        // 提取前五天的数据
        List<Object> objectList = dailyArray.subList(0, 5);
        // 将前五天的数据转换为JSON字符串
        String firstFiveDaysJson = JSON.toJSONString(objectList);
        map.put("5dayWeather", JSON.parseObject(firstFiveDaysJson,  new TypeReference<List<HashMap<String, Object>>>() {}));
        //获取灵川县今天的空气质量
        String s3 = doGet(AIR_NOW);
        jsonObject = JSON.parseObject(s3);
        String airNow = jsonObject.getString("now");
        map.put("todayAir", JSON.parseObject(airNow, HashMap.class));
        return Result.success(map);
    }



    public  String   doGet(String  url)  throws  Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String string = EntityUtils.toString(entity);
        response.close();
        httpClient.close();
        return  string;
    }

}




